package java_class_work.week08.internet.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @Author Tiam
 * @Date 2022/10/31 18:24
 * @Description:
 */
public class Receive implements Runnable {
    DatagramSocket ds = null;

    Receive(DatagramSocket ds){
        this.ds = ds;
    }

    @Override
    public void run() {
        String mess = null;
        do {
            mess = receiveMessage();
            System.out.println(mess);
        } while (!"stop".equalsIgnoreCase(mess));
        System.out.println("接收端已停止");
    }

    /**
     * 接收消息
     *
     * @return
     */
    private String receiveMessage() {
        String message = null;
        try {
            // 1. 新建服务
            // ds = new DatagramSocket(6666);
            // 2. 接收消息, 封装获取到的消息
            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
            ds.receive(dp);
            InetAddress address = dp.getAddress();
            System.out.print("发送端信息:" + address.toString()+": ");
            byte[] data = dp.getData();
            message = new String(data, 0, dp.getLength());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3. 关闭服务
            if (ds != null) ds.close();
        }
        return message;
    }
}
